#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowTitle("Server");

    ui->port->setText("8899");

    // 创建监听的服务器对象
    m_server = new QTcpServer(this);

    connect(m_server, &QTcpServer::newConnection, this, [=]()
    {
        m_tcp = m_server->nextPendingConnection();
        m_status->setPixmap(QPixmap(":/connect.png").scaled(20, 20));
        ui->record->append("there is a new connection...");

        // 检测是否可以接收数据
        connect(m_tcp, &QTcpSocket::readyRead, this, [=]()
        {
            QByteArray data = m_tcp->readAll();
            ui->record->append("Client Say: " + data);
        });

        connect(m_tcp, &QTcpSocket::disconnected, this, [=]()
        {
//            m_tcp->close();
//            m_tcp->deleteLater();
            m_status->setPixmap(QPixmap(":/disconnect.png").scaled(20, 20));
            ui->record->append("there is a Client disconnect...");
        });
    });

    // 状态栏
    m_status = new QLabel;
    m_status->setPixmap(QPixmap(":/disconnect.png").scaled(20, 20));
    ui->statusbar->addWidget(new QLabel("Connect Status: "));
    ui->statusbar->addWidget(m_status);
}

MainWindow::~MainWindow()
{
    m_tcp->close();
    m_tcp->deleteLater();
    delete ui;
}


void MainWindow::on_setListen_clicked()
{
    unsigned short port = ui->port->text().toUShort();
    m_server->listen(QHostAddress::Any, port);    
    ui->setListen->setEnabled(false);
    ui->record->append("Server starts listening...");
}

void MainWindow::on_sendMsg_clicked()
{
    QString msg = ui->msg->toPlainText();
    qDebug() << "m_tcp -- " << m_tcp;

    qint64 res = m_tcp->write(msg.toUtf8());
    // 这里检查如果真正读到了数据，记录才显示
    if(res > 0)
    {
        ui->record->append("Server Say: " + msg);
        ui->msg->setText("");
    }
    else
    {
        ui->record->append("Connect error, check Server or Client please...");
    }
}
